package com.quectel.core.module.partybuildingsurvey.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partybuildingsurvey.dao.PartySurveyPersonBindingDao;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyPersonBindingDto;
import com.quectel.core.module.partybuildingsurvey.entity.PartySurveyPersonBindingEntity;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyPersonBindingService;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:38
 */
@DubboService
public class PartySurveyPersonBindingServiceImpl implements PartySurveyPersonBindingService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartySurveyPersonBindingServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_SURVEY_PERSON_BINDING_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_SURVEY_PERSON_BINDING_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartySurveyPersonBindingDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_SURVEY_PERSON_BINDING_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartySurveyPersonBindingDao partySurveyPersonBindingDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private PartyPersonService partyPersonService;
    @Autowired
    private PartySurveyService partySurveyService;


    @Override
    public int querySurveyTotal(Map<String, Object> params){
        return partySurveyPersonBindingDao.querySurveyTotal(params);
    }
    @Override
    public List<PartySurveyPersonBindingDto> querySurveyList(Map<String,Object> params){
        List<PartySurveyPersonBindingEntity> list = partySurveyPersonBindingDao.querySurveyList(params);
        List<PartySurveyPersonBindingDto> result =  CopyUtils.copyList(list,PartySurveyPersonBindingDto.class);
        result.forEach(this::paddingField);
        return result;
    }


    @Override
    public PartySurveyPersonBindingDto selectBySurveyIdAndPersonId(Long surveyId,Long personId) {
        PartySurveyPersonBindingEntity entity = partySurveyPersonBindingDao.selectOne(new LambdaQueryWrapper<PartySurveyPersonBindingEntity>()
                .eq(PartySurveyPersonBindingEntity::getPartySurveyId, surveyId)
                .eq(PartySurveyPersonBindingEntity::getPersonId, personId)
                .last(SqlConstants.MYSQL_LIMIT_ONE)
        );
        PartySurveyPersonBindingDto partySurveyPersonBindingDto =CopyUtils.copyObj(entity, PartySurveyPersonBindingDto.class);
        return partySurveyPersonBindingDto;
    }

    @Override
    public List<PartySurveyPersonBindingDto> selectBySurveyId(Long surveyId) {
        List<PartySurveyPersonBindingEntity> list = partySurveyPersonBindingDao.selectList(new LambdaQueryWrapper<PartySurveyPersonBindingEntity>().eq(PartySurveyPersonBindingEntity::getPartySurveyId, surveyId));
        List<PartySurveyPersonBindingDto> result =  CopyUtils.copyList(list,PartySurveyPersonBindingDto.class);
        return result;
    }

    @Override
    public void deleteBySurveyId(Long surveyId) {
        partySurveyPersonBindingDao.delete(new LambdaQueryWrapper<PartySurveyPersonBindingEntity>()
                .eq(PartySurveyPersonBindingEntity::getPartySurveyId, surveyId));
    }

    @Override
    public PartySurveyPersonBindingDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_SURVEY_PERSON_BINDING_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartySurveyPersonBindingDto selectById(Long id){
            PartySurveyPersonBindingEntity entity = partySurveyPersonBindingDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,PartySurveyPersonBindingDto.class));
    }

    @Override
    public List<PartySurveyPersonBindingDto> queryList(Map<String,Object> params){
        List<PartySurveyPersonBindingEntity> list = partySurveyPersonBindingDao.queryList(params);
        List<PartySurveyPersonBindingDto> result =  CopyUtils.copyList(list,PartySurveyPersonBindingDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartySurveyPersonBindingDto paddingField(PartySurveyPersonBindingDto dto){
        if (dto != null){
            PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(dto.getPersonId());
            if (partyPersonDto != null) {
                //匿名
                if(SystemConstants.YES.equals(dto.getAnonymous())){
                    dto.setPersonName("匿名");
                    dto.setPersonMobile("");
                }else{
                    dto.setPersonName(partyPersonDto.getName());
                    dto.setPersonMobile(partyPersonDto.getMobile());
                }

                PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(partyPersonDto.getPartyId());
                if (partyOrganizationDto != null) {
                    dto.setPartyName(partyOrganizationDto.getName());
                }
            }
            PartySurveyDto partySurveyDto = partySurveyService.selectCacheById(dto.getPartySurveyId());
            if(partySurveyDto!=null){
                dto.setPartySurveyName(partySurveyDto.getName());
                dto.setPartySurveyStartTime(partySurveyDto.getStartTime());
                dto.setPartySurveyEndTime(partySurveyDto.getEndTime());
                dto.setPartySurveyStatus(partySurveyDto.getPartySurveyStatus());
                dto.setKnowResult(partySurveyDto.getKnowResult());
            }

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partySurveyPersonBindingDao.queryTotal(params);
    }

    @Override
    public Long save(PartySurveyPersonBindingDto dto){
        PartySurveyPersonBindingEntity entity = CopyUtils.copyObj(dto,PartySurveyPersonBindingEntity.class);
        entity.setId(Snowflake.nextId());
        partySurveyPersonBindingDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartySurveyPersonBindingDto dto){
        PartySurveyPersonBindingEntity entity = CopyUtils.copyObj(dto,PartySurveyPersonBindingEntity.class);

        partySurveyPersonBindingDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartySurveyPersonBindingDto dto) {
       PartySurveyPersonBindingEntity entity = CopyUtils.copyObj(dto,PartySurveyPersonBindingEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partySurveyPersonBindingDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partySurveyPersonBindingDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
